from lxml import etree
from util.selenium.webdriver.common.by import By

from spider_data.spiderBaseMethod import bm
from util.g import g

page_datas = {
    'record_year': 0,
    'r_index': 0
}




def get_content(driver=None):
    try:
        # # # TODO 获取各个年份的 按钮， 封装。（每次页面跳转都需要再次点击选项卡，并且之前定位的元素对象会失效。）
        WriteRdcostForm = list()
        years = bm.year_objs(driver=driver)
        for y_index, y in enumerate(years, 1):
            year_loc = (By.CSS_SELECTOR, f'.tab-box ul#attendance li:nth-of-type({y_index}) a')
            if y_index != 1:
                years = bm.year_objs(driver=driver)
                years[y_index - 1].click()

            record_year = driver.find_element(*year_loc).text
            record_year = int(record_year) if type(record_year) == str else record_year

            page_datas['record_year'] = record_year

            i = 1
            while True:
                text = driver.page_source
                # record_loc = (By.CSS_SELECTOR, 'tbody.tableBody tr')
                # records = driver.find_elements(*record_loc)
                tree = etree.HTML(text)
                records = tree.xpath("//tbody[@class='tableBody']/tr")

                # pn_loc = (By.CSS_SELECTOR, g.page_css + f':nth-of-type({p_index})')
                # print(len(records))
                for r_index, r in enumerate(records, 1):
                    page_datas['r_index'] = r_index

                    # operate_btn_loc = (By.CSS_SELECTOR, f'tbody.tableBody tr:nth-of-type({r_index}) td:last-child a')

                    # bm.wait(driver=driver, ele_loc=operate_btn_loc)
                    # driver.find_element(*operate_btn_loc).click()

                    # text = driver.page_source
                    rdcost_item = dict()

                    rdcost_item["rd_id"] = bm.get_ids(r.xpath("./td[2]/text()"))
                    rdcost_item["int_amount"] = bm.get_float_str(r.xpath("./td[3]/text()"))
                    rdcost_item["int_labor"] = bm.get_float_str(r.xpath("./td[4]/text()"))
                    rdcost_item["int_direct_inv"] = bm.get_float_str(r.xpath("./td[5]/text()"))
                    rdcost_item["int_de_lta"] = bm.get_float_str(r.xpath("./td[6]/text()"))
                    rdcost_item["int_aia"] = bm.get_float_str(r.xpath("./td[7]/text()"))
                    rdcost_item["int_design"] = bm.get_float_str(r.xpath("./td[8]/text()"))
                    rdcost_item["int_ecct"] = bm.get_float_str(r.xpath("./td[9]/text()"))
                    rdcost_item["int_other"] = bm.get_float_str(r.xpath("./td[10]/text()"))
                    rdcost_item["ext_amount"] = bm.get_float_str(r.xpath("./td[11]/text()"))
                    rdcost_item["ext_inchina"] = bm.get_float_str(r.xpath("./td[12]/text()"))
                    rdcost_item["amount"] = bm.get_float_str(r.xpath("./td[13]/text()"))
                    rdcost_item["reporter"] = bm.get_first(r.xpath("./td[14]/text()"))
                    rdcost_item["sig_date"] = bm.str_to_date(r.xpath("./td[15]/text"))
                    rdcost_item["sort_num"] = bm.get_num(r.xpath("./td[16]/text()"))
                    WriteRdcostForm.append(rdcost_item)
                    # parse_data(driver=driver, text=text)
                    # # # TODO 每次点击返回列表之后需要重新选择年份和页数。
                    if y_index != 1 and r_index != 1:
                        bm.wait(driver=driver, ele_loc=year_loc)
                        driver.find_element(*year_loc).click()
                    # if i != 1 and r_index != 1:
                    if i != 1:
                        # bm.wait(driver=driver, ele_loc=pn_loc)
                        # driver.find_element(*pn_loc).click()
                        # 跳转到第 i 页
                        show_last_page_btn_loc = (
                        By.CSS_SELECTOR, ".pagination.pull-right li:nth-of-type(3) a:nth-of-type(5)")
                        start_page = 5
                        while True:
                            # if i > start_page:
                            #     bm.click(driver=driver, ele_loc=show_last_page_btn_loc)
                            if i > start_page:
                                start_page += 2
                                bm.click(driver=driver, ele_loc=show_last_page_btn_loc)
                            else:
                                aim_page = (By.XPATH,
                                            """//ul[@class='pagination pull-right']/li[3]/a[text() = '{}']""".format(i))
                                bm.click(driver=driver, ele_loc=aim_page)
                                break

                        bm.wait(driver=driver, ele_loc=g.table_loc)

                next_btn = bm.get_ele(driver=driver, ele_loc=g.next_btn_loc)
                onclick = None
                try:
                    onclick = next_btn.get_attribute("onclick")
                except Exception as err:
                    g.logger.error("get next page button\' attribute error: {}".format(err))
                if onclick is None:
                    break
                else:
                    bm.click(driver=driver, ele_loc=g.next_btn_loc)
                    bm.wait(driver=driver, ele_loc=g.table_loc)
                    i += 1
        # driver.switch_to.default_content()
        return {"key": "WriteRdcostForm", "value": WriteRdcostForm}
    except Exception as err:
        msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                    err.__traceback__.tb_lineno)
        g.logger.error(msg)
        raise Exception(msg)


def parse_rdcost(driver=None):
    try:
        rdcost_loc = (By.LINK_TEXT, '企业年度研究开发费用结构明细表')

        bm.detail_switch_iframe(driver=driver)

        bm.wait(driver=driver, ele_loc=rdcost_loc)
        driver.find_element(*rdcost_loc).click()

        bm.wait(driver=driver, ele_loc=g.title_loc)

        get_content(driver=driver)
    except Exception as err:
        msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                    err.__traceback__.tb_lineno)
        g.logger.error(msg)
        raise Exception(msg)


# def parse_data(driver=None, text=''):
#     try:
#         text = text.replace('<div class="line"></div>', '')
#         tree = etree.HTML(text)
#         # # # TODO 因为页面中没有排序号相关信息， 所以将表格顺序当做排序号填入。
#         rdcost_item = {'co_id': g.co_id, 'year': g.commit_date, 'peryear': page_datas.get('record_year'), 'rd_id': '',
#                        # 总发生额（万元）   人员人工   直接投入   折旧费用与长期待摊   无形资产摊销   设计   装备调试费用与试验   其他   委托外部研究开发费用-总发生额（万元）   委托外部研究开发费用-境内的外部研发   内外部费用总额（万元）
#                        'int_amount': '', 'int_labor': '', 'int_direct_inv': '', 'int_de_lta': '', 'int_aia': '', 'int_design': '', 'int_ecct': '', 'int_other': '', 'ext_amount': '', 'ext_inchina': '', 'amount': '',
#                        'reporter': '', 'sig_date': '', 'sort_num': page_datas.get('r_index')}
#         rd_id_name = join_and_repalce(tree.xpath('//h2[@class="text-center"]/small/text()'))
#         rdcost_item["rd_id_name"] = rd_id_name
#         rdcost_item['rd_id'] = bm.get_ids(id_str=rd_id_name)
#
#         cost = get_first(tree.xpath('//div[@class="box-body"]/div[1]'))
#
#         int_amount = cost.xpath('./h3[1]/text()')
#         rdcost_item['int_amount'] = handle_rdcost.get_float(int_amount)
#
#         int_labor = cost.xpath('./div[1]/div[1]//small/text()')
#         rdcost_item['int_labor'] = handle_rdcost.get_float(int_labor)
#         int_direct_inv = cost.xpath('./div[1]/div[2]//small/text()')
#         rdcost_item['int_direct_inv'] = handle_rdcost.get_float(int_direct_inv)
#         int_de_lta = cost.xpath('./div[2]/div[1]//small/text()')
#         rdcost_item['int_de_lta'] = handle_rdcost.get_float(int_de_lta)
#         int_aia = cost.xpath('./div[2]/div[2]//small/text()')
#         rdcost_item['int_aia'] = handle_rdcost.get_float(int_aia)
#         int_design = cost.xpath('./div[3]/div[1]//small/text()')
#         rdcost_item['int_design'] = handle_rdcost.get_float(int_design)
#         int_ecct = cost.xpath('./div[3]/div[2]//small/text()')
#         rdcost_item['int_ecct'] = handle_rdcost.get_float(int_ecct)
#         int_other = cost.xpath('./div[4]/div[1]//small/text()')
#         rdcost_item['int_other'] = handle_rdcost.get_float(int_other)
#
#         # outter_cost = get_first(tree.xpath('//div[@class="box-body"]/div[2]'))
#
#         ext_amount = cost.xpath('./h3[2]/text()')
#         rdcost_item['ext_amount'] = handle_rdcost.get_float(ext_amount)
#         ext_inchina = cost.xpath('./div[5]/div[1]//small/text()')
#         rdcost_item['ext_inchina'] = handle_rdcost.get_float(ext_inchina)
#
#         amount = cost.xpath('./h3[3]/text()')
#         rdcost_item['amount'] = handle_rdcost.get_float(amount)
#
#         # sign_info = get_first(tree.xpath('//div[@class="box-body"]/div[3]/div[@class="right-p"]'))
#
#         reporter = cost.xpath('./div[6]/div[1]//small/text()')
#         rdcost_item['reporter'] = join_and_repalce(reporter)
#         sig_date = cost.xpath('./div[6]/div[2]//small/text()')
#         # print(sig_date)
#         rdcost_item['sig_date'] = handle_rdcost.str_to_date(sig_date)
#
#         # # # TODO 处理小数问题，先将数据从列表中取出， 判断其是否为小数，是则直接使用 Decimal 转换， 否则使用正则匹配出小数， 然后进行转换。
#         # # # TODO 处理日期问题。
#
#         # print(f'int_amount---{int_amount}\n int_labor---{int_labor}\n int_direct_inv---{int_direct_inv}\n int_de_lta---{int_de_lta}\n int_aia---{int_aia}\n int_design---{int_design}\n int_ecct---{int_ecct}\n int_other---{int_other}\n ext_amount---{ext_amount}\n ext_inchina---{ext_inchina}\n amount---{amount}\n reporter---{reporter}\nsig_date---{sig_date}\n\n')
#
#         # print(rdcost_item)
#         # # #  点击返回列表按钮。
#         SaveData().save(table='ent_res_rdcost', value=rdcost_item)
#
#
#         back_list_loc = (By.CSS_SELECTOR, 'h2.text-center a.left-b')
#         bm.wait(driver=driver, ele_loc=back_list_loc)
#         driver.find_element(*back_list_loc).click()
#     except Exception as err:
#         msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
#                                                     err.__traceback__.tb_lineno)
#         g.logger.error(msg)
#         raise Exception(msg)
